package org.huangrui.redis.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author hr
 * @Create 2024-05-15 15:24
 */
@Slf4j
@Service
public class GeoService {
    public static final String CITY ="city";
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public String geoAdd() {
        Map<String, Point> map = new HashMap<>();
        map.put("天安门",new Point(116.403963,39.915119));
        map.put("故宫",new Point(116.403414,39.924091));
        map.put("长城",new Point(116.024067,40.362639));
        redisTemplate.opsForGeo().add(CITY,map);
        return map.toString();
    }

    public Point position(String member) {
        // 获取经纬度坐标
        List<Point> points = redisTemplate.opsForGeo().position(CITY, member);
        assert points != null;
        return points.get(0);
    }

    public String hash(String member) {
        // geohash算法生成的base32编码值
        List<String> list = redisTemplate.opsForGeo().hash(CITY, member);
        assert list != null;
        return list.get(0);
    }

    public Distance distance(String member1, String member2) {
        // 获取两个给定位置之间的距离
        return redisTemplate.opsForGeo().distance(CITY, member1, member2, RedisGeoCommands.DistanceUnit.KILOMETERS);
    }


    public GeoResults<RedisGeoCommands.GeoLocation<String>> radiusByxy() {
        //通过经度，纬度查找附近的,北京王府井位置116.418017,39.914402
        Circle circle = new Circle(116.418017,39.914402, Metrics.KILOMETERS.getMultiplier());
        // 返回50条
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().includeCoordinates().limit(50);
        return redisTemplate.opsForGeo().radius(CITY, circle, args);
    }


    public GeoResults<RedisGeoCommands.GeoLocation<String>> radiusByMember() {
        //半径10公里内
        Distance distance=new Distance(10, Metrics.KILOMETERS);
        // 返回50条
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().includeCoordinates().limit(50);
        return redisTemplate.opsForGeo().radius(CITY, "天安门",distance,args);
    }
}
